package club.easin.spring;

import club.easin.utils.CheckUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware, DisposableBean {

    protected static ApplicationContext context;
    private static final Logger logger = LoggerFactory.getLogger(SpringContext.class);
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context=applicationContext;
    }

    public ApplicationContext getContext(){
        return context;
    }

    public static Object getBeanByName(String beanName){
        if(CheckUtils.isNull(beanName)){
            return null;
        }else {
            return context.getBean(beanName);
        }
    }

    @Override
    public void destroy() throws Exception {
        logger.debug("清除 SpringContext 中的 ApplicationContext: {}", context);
        context = null;

    }
}
